package com.xique.door.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.core.web.domain.PageResult;
import com.xique.door.bean.domain.ResourceBit;
import com.xique.door.bean.domain.SysUser;
import com.xique.door.bean.vo.advert.AppAdvertVo;
import com.xique.door.constant.ResourcePositionConstant;
import com.xique.door.mapper.ResourceBitMapper;
import com.xique.door.service.IResourceBitService;
import com.xique.door.service.ISysUserService;
import com.xique.door.util.RedisUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ResourceBitServiceImpl extends ServiceImpl<ResourceBitMapper, ResourceBit>
        implements IResourceBitService {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public PageResult getResourceBitList(
            ResourceBit resourceBit,
            String startTime,
            String endTime,
            Integer pageNum,
            Integer pageSize,
            String userName,
            String exhibitionStatus) {
        QueryWrapper<ResourceBit> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "id,theme,title,position,put_starttime,put_endtime,status,create_time,update_time,create_user,update_user,picture_url,url,exhibition,picturesort,file_type,position_type,"
                        + "CASE WHEN put_starttime >= NOW( ) THEN'未开始' "
                        + "WHEN put_starttime <= NOW( ) && put_endtime >= NOW( ) THEN'展示中' "
                        + "WHEN put_starttime <= NOW( ) && put_endtime IS NULL THEN'展示中' "
                        + "WHEN put_endtime <= NOW( ) THEN'已结束' ELSE '未知' END exhibition_status");
        if (resourceBit.getPosition() != null && !"".equals(resourceBit.getPosition())) {
            queryWrapper.eq("position", resourceBit.getPosition());
        }
        if (resourceBit.getTheme() != null && !"".equals(resourceBit.getTheme())) {
            queryWrapper.like("theme", resourceBit.getTheme());
        }
        if (startTime != null && !"".equals(startTime) && endTime != null && !"".equals(endTime)) {
            queryWrapper.between("put_starttime", startTime, endTime);
        }
        if (startTime != null && !"".equals(startTime)) {
            queryWrapper.ge("put_starttime", startTime);
        }
        if (userName != null && !"".equals(userName)) {
            SysUser sysUser = sysUserService.getSysUser(null, userName);
            if (sysUser != null) {
                queryWrapper.eq("update_user", sysUser.getUserId());
            } else {
                queryWrapper.isNull("update_user");
            }
        }
        if (exhibitionStatus != null && !"".equals(exhibitionStatus)) {
            if (exhibitionStatus.equals("未开始")) {
                queryWrapper.ge("put_starttime", new Date());
            } else if (exhibitionStatus.equals("展示中")) {
                queryWrapper.le("put_starttime", new Date());
                queryWrapper.and(wrappers -> wrappers.ge("put_endtime", new Date()).or().isNull("put_endtime"));
            } else if (exhibitionStatus.equals("已结束")) {
                queryWrapper.le("put_endtime", new Date());
            }
        }
        queryWrapper.orderByDesc("create_time");
        Page<ResourceBit> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<ResourceBit> list = baseMapper.selectPage(page, queryWrapper);

        List<ResourceBit> lists = list.getRecords();
        if (lists.size() > 0) {
            for (ResourceBit resourceBit1 : lists) {
                SysUser sysUser = sysUserService.getSysUser(resourceBit1.getUpdateUser(), null);
                if (sysUser != null) {
                    resourceBit1.setUpdateUserName(sysUser.getUserName());
                }
            }
        }
        long totalPages = list.getPages();
        long totalSize = list.getTotal();
        return PageResult.builder()
                .pageNum(pageNum)
                .pageSize(pageSize)
                .totalPages(totalPages)
                .totalSize(totalSize)
                .list(list.getRecords())
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public R insertResourceBit(ResourceBit resourceBit) {
        resourceBit.setCreateTime(new Date());
        resourceBit.setCreateUser(SecurityUtils.getUserId());
        resourceBit.setUpdateUser(SecurityUtils.getUserId());
        resourceBit.setStatus("1");
        if (resourceBit.getFileType() == null) {
            resourceBit.setFileType(1);
        }

        List<ResourceBit> voList = new ArrayList<>();
        if (resourceBit.getPosition().equals("6")||resourceBit.getPosition().equals("7")
                || resourceBit.getPosition().equals("1")
                || resourceBit.getPosition().equals("4")
                || resourceBit.getPosition().equals("5")
                || (null != resourceBit.getPositionType() && resourceBit.getPositionType().equals("1"))) {
            voList =
                    getResourceBitList(resourceBit.getPosition(),
                            resourceBit.getPutStarttime(),
                            resourceBit.getPicturesort(),
                            resourceBit.getPositionType());

            if (resourceBit.getPosition().equals("2") || (null != resourceBit.getPositionType() && resourceBit.getPositionType().equals("2"))) {
                voList = getResourceMiniList(resourceBit.getPosition(),
                        resourceBit.getPutStarttime(),
                        resourceBit.getResourceType(),
                        resourceBit.getPicturesort(),
                        resourceBit.getPositionType());
            }

            if (voList.size() > 0) {
                return R.fail("该时间段内已有资源");
            }
            if (resourceBit.getPosition().equals("6")) {
                List<ResourceBit> voList1 =
                        getResourceBitList(resourceBit.getPosition(), resourceBit.getPutStarttime(), resourceBit.getPicturesort(), null);
                if (voList1.size() > 2) {
                    return R.fail("排序错误");
                }
            }
        }
        int rep = baseMapper.insert(resourceBit);
        if (rep > 0) {
            return R.ok(null, "添加成功");
        }
        return R.fail("添加失败");
    }

    private List<ResourceBit> getResourceMiniList(String position, Date putStarttime, Integer resourceType, Integer picturesort, String positionType) {

        QueryWrapper<ResourceBit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("position", position);
        queryWrapper.eq("status", "1");
        queryWrapper.ge("put_endtime", putStarttime);
        queryWrapper.eq("resource_type", resourceType);
        if (positionType != null && !"".equals(positionType)) {
            queryWrapper.eq("position_type", positionType);
        }
        if (picturesort != null) {
            queryWrapper.eq("picturesort", picturesort);
        }
        List<ResourceBit> list = baseMapper.selectList(queryWrapper);
        return list;
    }

    public List<ResourceBit> getResourceBitList(
            String position, Date putStarttime, Integer picturesort, String positionType) {
        QueryWrapper<ResourceBit> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("position", position);
        queryWrapper.eq("status", "1");
        queryWrapper.ge("put_endtime", putStarttime);
        if (positionType != null && !"".equals(positionType)) {
            queryWrapper.eq("position_type", positionType);
        }
        if (picturesort != null) {
            queryWrapper.eq("picturesort", picturesort);
        }
        List<ResourceBit> list = baseMapper.selectList(queryWrapper);
        return list;
    }


    @Override
    public R getResourceBit(Long id) {
        return R.ok(baseMapper.selectById(id));
    }

    @Override
    public R updateResourceBit(ResourceBit resourceBit) {
        if (resourceBit.getPosition().equals("6")
                || resourceBit.getPosition().equals("1")
                || resourceBit.getPosition().equals("2")
                || resourceBit.getPosition().equals("4")
                || resourceBit.getPosition().equals("5")
                || (null != resourceBit.getPositionType() && resourceBit.getPositionType().equals("1"))
                || (null != resourceBit.getPositionType() && resourceBit.getPositionType().equals("2"))) {
            List<ResourceBit> voList =
                    getResourceBitList(
                            resourceBit.getPosition(),
                            resourceBit.getPutStarttime(),
                            resourceBit.getPicturesort(), resourceBit.getPositionType());
            if (voList.size() > 0) {
                for (ResourceBit bit : voList) {
                    if (!bit.getId().equals(resourceBit.getId())) {
                        return R.fail("该时间段内已有资源");
                    }
                }
            }
            if (resourceBit.getPosition().equals("6")) {
                List<ResourceBit> voList1 =
                        getResourceBitList(resourceBit.getPosition(), resourceBit.getPutStarttime(), resourceBit.getPicturesort(), null);
                if (voList1.size() > 2) {
                    return R.fail("排序错误");
                }
            }
        }
        int rep = baseMapper.updateById(resourceBit);
        if (rep > 0) {
            return R.ok(null, "修改成功");
        }
        return R.fail("修改失败");
    }

    @Override
    public R updateStatus(Long id, String status) {
        if (status.equals("2")) {
            ResourceBit resourceBit = new ResourceBit();
            resourceBit.setId(id);
            resourceBit.setStatus(status);
            baseMapper.updateById(resourceBit);
            return R.ok(null, "修改状态成功");
        } else if (status.equals("1")) {
            QueryWrapper<ResourceBit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            ResourceBit r = baseMapper.selectOne(queryWrapper);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date s1 = r.getPutEndtime();
            if (r.getPosition().equals("6")
                    || r.getPosition().equals("1")
                    || r.getPosition().equals("2")
                    || r.getPosition().equals("4")
                    || r.getPosition().equals("5")) {
                List<ResourceBit> voList =
                        getResourceBitList(r.getPosition(), r.getPutStarttime(), r.getPicturesort(), r.getPositionType());
                if (voList.size() > 0) {
                    return R.fail("该时间段内已有资源");
                }
            }
            if (r.getPutEndtime() != null) {
                if (!s1.before(new Date())) {
                    ResourceBit resourceBit = new ResourceBit();
                    resourceBit.setId(id);
                    resourceBit.setStatus(status);
                    baseMapper.updateById(resourceBit);
                    return R.ok(null, "修改状态成功");
                } else {
                    return R.fail("超出发布结束时间");
                }
            } else {
                ResourceBit resourceBit = new ResourceBit();
                resourceBit.setId(id);
                resourceBit.setStatus(status);
                baseMapper.updateById(resourceBit);
                return R.ok(null, "修改状态成功");
            }
        }
        return R.fail("修改状态失败");
    }

    @Override
    public R deleteResourceBit(Long id) {
        baseMapper.deleteById(id);
        return R.ok(null, "删除成功");
    }
    @Override
    public AjaxResult getAdvertisementList(Integer position, Integer positionType) {
        LambdaQueryWrapper<ResourceBit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResourceBit::getPosition,position)
                .eq(ResourceBit::getPositionType,positionType).eq(ResourceBit::getStatus,1);
        queryWrapper.le(ResourceBit::getPutStarttime,new Date());
        queryWrapper.ge(ResourceBit::getPutEndtime,new Date());
        queryWrapper.orderByDesc(ResourceBit::getPicturesort);
        List<ResourceBit> list = this.list(queryWrapper);
        ArrayList<AppAdvertVo> appAdvertVos = new ArrayList<>();
        list.forEach(resourceBit -> {
            AppAdvertVo appAdvertVo = new AppAdvertVo();
            BeanUtils.copyProperties(resourceBit,appAdvertVo);
            appAdvertVos.add(appAdvertVo);
        });
        return AjaxResult.success(appAdvertVos);
    }


}
